<?php

  function getPageRating($url, $url_param) {
    $return_string = "";
   
    $query = "SELECT id FROM WebPage WHERE url = '" . $url . "'";
    $result = mysql_query($query);
    $webpage_id = -1;
    if (mysql_num_rows($result) == 0) {
      $webpage_id = registerPage($url);
    } else {
      $result_row = mysql_fetch_assoc($result);
      $webpage_id = $result_row['id'];
    }

    $webpagequery_id = getPageParameterId($webpage_id, $url_param);

    $query = "SELECT (ROUND(AVG(rating),2)) AS avgRating FROM WebPageRating"
           . " WHERE webpagequery_id=$webpagequery_id";
    $result = mysql_query($query);  
    $result_row = mysql_fetch_assoc($result);
    $average_rating = $result_row['avgRating'];
    $return_string .= "<averagerating>$average_rating</averagerating>\n";

    if (isset($_SESSION['user_id'])) {
      $user_id = $_SESSION['user_id'];
      $query = "SELECT * FROM WebPageRating WHERE user_id=$user_id"
             . " AND webpagequery_id=$webpagequery_id";
      $result = mysql_query($query);
      
      if (mysql_num_rows($result) > 0) {
        $result_row = mysql_fetch_assoc($result);
        $user_rating = $result_row['rating'];
        $return_string .= "<userrating>$user_rating</userrating>\n";
      } else {
        $return_string .= "<userrating>0</userrating>\n";
      }
    } else {
      $return_string .= "<userrating>0</userrating>\n";
    }
    return $return_string;
  }
?>
